
using Abp.Domain.Repositories;
using Abp.UI;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.Integratedes.Organization;
using SOEI.Solution.Integratedes.Organization.DomainService;
using SOEI.Solution.StructEntities.Organization;
using SOEI.Solution.ThirdParty.ESignClient.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThirdParty.ESignClient;

namespace SOEI.Solution.Integratedes.ElectronicSignet.DomainService
{
	/// <summary>
	/// 领域服务层一个模块的核心业务逻辑
	///</summary>
	public class SignetGrantManager :DomainServiceBase, ISignetGrantManager
	{
		
		private readonly IRepository<SignetGrant,long> _signetgrantRepository;

		/// <summary>
		/// 机构人员领域服务
		/// </summary>
		private readonly OEconomyPersonManager _economyPersonManager;

		/// <summary>
		/// E签宝
		/// </summary>
		private readonly IESignManager _eSignManager;

		/// <summary>
		/// 【SignetGrant】的构造方法
		/// 通过构造函数注册服务到依赖注入容器中
		///</summary>
		public SignetGrantManager(
			IRepository<SignetGrant, long> signetgrantRepository,
			OEconomyPersonManager economyPersonManager,
			IESignManager eSignManager
		)	{
			_signetgrantRepository =  signetgrantRepository;
			_economyPersonManager = economyPersonManager;
			_eSignManager = eSignManager;
		}

		#region -------------------------------------------------辅助工具生成---------------------------------------------- 

		/// <summary>
		/// 返回列表查询用
		/// </summary>
		/// <returns></returns>
		public IQueryable<SignetGrant> QueryEntityListAsNoTracking() { 

			var query = _signetgrantRepository.GetAll().AsNoTracking()
						.Select(x => new SignetGrant
						{
						    Id   = x.Id,
							RYBH = x.RYBH,
							SQZT = x.SQZT,
							SQFS = x.SQFS,
							SXRQ = x.SXRQ,
							JGBH = x.JGBH,
							Remark=x.Remark,
							CreationTime = x.CreationTime,
							CreatorUserId = x.CreatorUserId,
							LastModificationTime=x.LastModificationTime,
							LastModifierUserId = x.LastModifierUserId
						});
			return query;
		}

		/// <summary>
		/// 【SignetGrant】返回表达式数的实体信息即IQueryable类型
		/// </summary>
		/// <returns>IQueryable</returns>
		public IQueryable<SignetGrant> Query()
		{
			return _signetgrantRepository.GetAll();
		}
		/// <summary>
		/// 【SignetGrant】返回即IQueryable类型的实体，不包含EF Core跟踪标记
		/// </summary>
		/// <returns>IQueryable</returns>
		public IQueryable<SignetGrant> QueryAsNoTracking()
		{
			return _signetgrantRepository.GetAll().AsNoTracking();
		}
		/// <summary>
		/// 【SignetGrant】根据Id查询实体信息
		/// </summary>
		/// <param name="id"></param>
		/// <returns>实体</returns>
		public async Task<SignetGrant> FindByIdAsync(long id)
		{
			var entity = await _signetgrantRepository.GetAsync(id);
			return entity;
		}
		/// <summary>
		/// 【SignetGrant】检查实体是否存在
		/// </summary>
		/// <param name="id"></param>
		/// <returns>bool</returns>
		public async Task<bool> IsExistAsync(long id)
		{
			var result = await _signetgrantRepository.GetAll().AnyAsync(a => a.Id == id);
			return result;
		}
		/// <summary>
		/// 【SignetGrant】创建实体
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public async Task<SignetGrant> CreateAsync(SignetGrant entity)
		{
			entity.Id = await _signetgrantRepository.InsertAndGetIdAsync(entity);
			return entity;
		}
		/// <summary>
		/// 【SignetGrant】更新实体
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public async Task UpdateAsync(SignetGrant entity)
		{
			await _signetgrantRepository.UpdateAsync(entity);
		}
		/// <summary>
		/// 【SignetGrant】删除实体
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public async Task DeleteAsync(long id)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _signetgrantRepository.DeleteAsync(id);
		}
		/// <summary>
		/// 【SignetGrant】批量删除
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task BatchDelete(List<long> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _signetgrantRepository.DeleteAsync(a => input.Contains(a.Id));
		}
		#endregion


		#region -------------------------------------------------用户自定义------------------------------------------------

		/// <summary>
		/// 获取机构电子签章账号
		/// </summary>
		/// <param name="SignetGrant">印章授权实体</param>
		/// <param name="Account">第三方用户账号</param>
		/// <returns></returns>
		public async Task<AccountModel> GetAccountModel(SignetGrant SignetGrant, AccountEntity Account)
		{
			TokenModel<AccountModel> result = null;

			if (string.IsNullOrEmpty(SignetGrant.AccountID))
			{
				// 不存在创建新的
				
				result = await this._eSignManager.CreateAccountAsync(Account);
			}
			else
			{
				// 存在则更新一下
				result = await this._eSignManager.UpdateAccountAsync(Account);
			}
			if (result.Code != "53000000")
			{
				if (!result.Success)
				{
					throw new UserFriendlyException(result.Message);
				}
			}
			// 6.获取个人账号信息
			var data = await this._eSignManager.GetAccountInfoAsync(SignetGrant.RYBH);

			return data.Data;
		}


		/// <summary>
		/// 获取人员信息表与电子印章授权表联合查询
		/// </summary>
		/// <returns></returns>
		public IQueryable<OurOrganiPerson> QueryUnionEntityListAsNoTracking()
		{
			// 1.主表为人员信息表
			var query = this._economyPersonManager.QueryUnionEntityListAsNoTracking();
			// 2.子表为SignetGrant
			var querySignetGrant = this.QueryAsNoTracking();

			var result = from x in query
						 join a in querySignetGrant on x.Id equals a.RYBH into dc
						 from dci in dc.DefaultIfEmpty()
						 select new OurOrganiPerson
						 {
							 Id = x.Id,
							 RYMC = x.RYMC,
							 LXDH = x.LXDH,
							 SFZH = x.SFZH,
							 JGBH = x.JGBH,
							 
							 SignetGrant = dci
							 /*
							 CreationTime = dci.CreationTime,
							 CreatorUserId = dci.CreatorUserId,
							 LastModificationTime = dci.LastModificationTime,
							 LastModifierUserId = dci.LastModifierUserId*/
						 };
			return result;
		}
		#endregion









	}
}
